import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_application_pd/common/models/notice.dart';
import 'package:flutter_application_pd/common/utils/index.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  LoginController();
  var usernamecontrol = TextEditingController();
  var passwordcontrol = TextEditingController();
  var notice = "";
  _initData() {
    getNotice();
    update(["login"]);
  }

  isLoggedIn() async {
    var store = await Store.getInstance();
    return store?.get('token') ?? "";
  }

  void getNotice() async {
    var response = await Api.instance.get('/login/huoqugonggao');

    notice = Notice.fromJson(jsonDecode(response.data)).data!.gonggao!;
  }

  void onTap() async {
    if (usernamecontrol.text.isEmpty || passwordcontrol.text.isEmpty) {
      Get.snackbar('提示', '用户名或密码不能为空');
      return;
    }
    if (usernamecontrol.text.length < 6 || passwordcontrol.text.length < 6) {
      Get.snackbar('提示', '用户名或密码不能小于6位');
      return;
    }
    var response = await Api.instance.post('/login/login', data: {
      "username": usernamecontrol.text,
      "password": passwordcontrol.text
    });
    var res = jsonDecode(response.data);

    // ignore: unrelated_type_equality_checks
    if (res['code'] == 0) {
      Get.snackbar('提示', '用户名或密码错误');
      return;
    } else {
      var store = await Store.getInstance();
      store?.set('token', res['data']['token']);
      Get.snackbar('提示', '登录成功！');
      Get.offAllNamed('/home');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
